package com.sso.ssologin.controller;

import java.util.HashSet;
// import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.Optional;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
//import org.thymeleaf.util.StringUtils;

import com.sso.ssologin.Pojo.User;
import com.sso.ssologin.utils.LoginCacheUtil;
import org.springframework.web.bind.annotation.CookieValue;



@Controller
// 映射
@RequestMapping("/login")
public class LoginController {

    private static Set<User> dbUsers;
    static{
        dbUsers = new HashSet<>();
        dbUsers.add(new User(0,"zhangsan","12345"));
        dbUsers.add(new User(1,"lisi","123456"));
        dbUsers.add(new User(2,"wangwu","1234567"));
    }

    @PostMapping
    public String doLogin(User user, HttpSession session, HttpServletResponse response){
        String target=(String) session.getAttribute("target");
        // 模拟从数据库中通过登录的用户名和密码去查找数据库中的用户
        Optional<User> first=dbUsers.stream().filter(dbUser -> dbUser.getUsername().equals(user.getUsername())&&
                                dbUser.getPassword().equals(user.getPassword())).findFirst();
        // 判断用户是否登录
        if(first.isPresent()){
            // 保存用户登录信息,写一个方法来缓存用户信息
            //随机生成刚登陆用户的token，并保存
            String token=UUID.randomUUID().toString();
            Cookie cookie = new Cookie("TOKEN",token);
            // cookie设置相同的域
            cookie.setDomain("sso.com");
            response.addCookie(cookie);
            LoginCacheUtil.loginUser.put(token, first.get());

        }
        else{
            // 登录失败
            session.setAttribute("msg","用户名或密码错误");
            return "login";
        }

        // 重定向到target地址
        return "redirect:"+target;
    }

    @GetMapping("info")
    @ResponseBody
    public ResponseEntity<User> getUserInfo(String token){
        if(!StringUtils.isEmpty(token)){
            //当token并不为空时，查询用户并响应
            User user =LoginCacheUtil.loginUser.get(token);
            return ResponseEntity.ok(user);
        }else{
            //若为空，响应错误请求
            return new ResponseEntity<>(null,HttpStatus.BAD_REQUEST);
        }

    }

    @GetMapping("/logout")
    public String loginOut(@CookieValue(value = "TOKEN") Cookie cookie,  HttpServletResponse response,HttpServletRequest request) {
        cookie.setMaxAge(0);
        LoginCacheUtil.loginUser.remove(cookie.getValue());
        Cookie[] cookies = request.getCookies();  
            if (null==cookies) {  
                System.out.println("没有cookie==============");  
            } else {  
                for(Cookie cook : cookies){  
                    if(cook.getName().equals("TOKEN")){  
                        cook.setValue(null);  
                        cook.setMaxAge(0);// 立即销毁cookie  
                        cook.setPath("/");  
                        System.out.println("被删除的cookie名字为:"+cook.getName());  
                        response.addCookie(cook);  
                        break;  
                    }  
                }  
            }  
        return "login";
    }
}
